package com.right.handler;

import com.right.command.CsCommand;
import com.right.db.Bicycle;
import com.right.factory.NodeStatus;
import com.right.mapper.BicycleMapper;
import com.right.mapper.CommonMapper;
import com.right.mapper.UnlockMapper;
import com.right.util.push.PushUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by ding on 2019/1/15.
 */
@Slf4j
public class BankCardUnlockHandler implements PackageHandler{
    private final UnlockMapper unlockMapper;
    private final BicycleMapper bicycleMapper;
    private final CommonMapper commonMapper;

    public BankCardUnlockHandler(UnlockMapper unlockMapper, BicycleMapper bicycleMapper, CommonMapper commonMapper) {
        this.unlockMapper = unlockMapper;
        this.bicycleMapper = bicycleMapper;
        this.commonMapper = commonMapper;
    }

    @Override
    public boolean applies(List<String> dataList) {
        return  CsCommand.BANK_CARD_UNLOCK.equals(dataList.get(0));
    }

    @Override
    public boolean handleMessage(ChannelHandlerContext ctx, List<String> dataList) {
        log.info("银行卡开锁");
        String lockNo = ctx.channel().attr(NodeStatus.LOCK_NO).get();
        String bankCardNo = dataList.get(1);
        Example o = new Example(Bicycle.class);
        o.createCriteria().andEqualTo("lockNo",lockNo);
        int i = bicycleMapper.selectCountByExample(o);
        if (i!= 1){
            log.error("未找到设备记录");
            return false;
        }else {
            //查找车辆信息
            Map<String,Object> bicycleMap =  unlockMapper.selectBicycleByLockNo(lockNo);
            String dockSiteNo = (String)bicycleMap.get("docksiteno");
            Long operatorId = (Long)bicycleMap.get("operator_id");
            Integer bicycleStatus = (Integer)bicycleMap.get("bicycle_status");
            String bicycleNo = (String)bicycleMap.get("bicycle_no");
            Long bicycleId = (Long)bicycleMap.get("id");
            Long dockSiteId = (Long)bicycleMap.get("docksiteid");
            //0待投放1可租2骑行3维修4报废5车辆故障6带回7维修完成8临停
            if (bicycleStatus !=1 && bicycleStatus!=8){
                log.error("自行车状态不正确");
                return false;
            }

            //获取费用信息
            int count =  unlockMapper.selectCountBicycleChargerule(String.valueOf(operatorId));
            if (count !=1){
                log.error("未找到费用记录");
                return false;
            }
            BigDecimal timeCharge = unlockMapper.selectBicycleChargerule(String.valueOf(operatorId));

            //银行卡是否开户
            int count1 = unlockMapper.selectCountA03bankcardByBankCardNo(bankCardNo);
            Map<String,Object> A03Map =null;
            String s = "401,0,0";
            String ss = "401,1,0";
            //未开户则不开锁
            if (count1 !=1){
                ctx.channel().writeAndFlush(s);
                unlockMapper.insertBicycleCreditCardRecords(bankCardNo,new Date(),2,-1);
                return false;
            }else {
                A03Map = unlockMapper.selectA03bankcardByBankCardNo(bankCardNo);
                String strBankUUid =(String) A03Map.get("id");
                String riderId =(String) A03Map.get("riderid");

                //判断该卡有没有正在租车记录开始
                int count2 = unlockMapper.selectCountBicycleRentByRiderId(riderId);
                if (count2>0){
                    if (bicycleStatus==8){
                        //查询租车id
                        Map<String ,Object> BicycleRentMap=  unlockMapper.selectBicycleRentByRiderId(riderId);
                        Long rentId =(Long) BicycleRentMap.get("id");
                        String bicycle_noStr =(String) BicycleRentMap.get("bicycle_no");
                        if (!bicycle_noStr.equals(bicycleNo)){
                            log.error("临停车辆不同");
                            ctx.channel().writeAndFlush(s);
                        }
                        //临停解锁修改begin
                        int count4 =  unlockMapper.selectCountBicycleTemporaryStopId(bicycleId,rentId,riderId);
                        if (count4 == 1){
                            Long bicycleTemporaryStopId =  unlockMapper.selectBicycleTemporaryStopId(bicycleId,rentId,riderId);

                            unlockMapper.updateBicycle(new Date(),bicycleId);
                            unlockMapper.updateBicycleTemporaryStop(3,new Date(),bicycleTemporaryStopId);

                            Integer putType = 22;
                            //增加推送消息
                            //获取设备信息
                            Map<String, Object> pdaUseronlineMap = commonMapper.selectPdaUseronlineByRiderId(riderId);
                            if (pdaUseronlineMap==null ||pdaUseronlineMap.size()==0){
                                return false;
                            }
                            //deviceId 设备id,deviceType设备类型
                            String deviceId =(String) pdaUseronlineMap.get("deviceid");
                            Integer deviceType = (Integer)pdaUseronlineMap.get("device_type");
                            PushUtil.pushToSingle(deviceId, deviceType,"临停开车成功","开锁",0,22);

                            ctx.channel().writeAndFlush(ss);
                        }
                    }
                    //临停解锁修改end
                    unlockMapper.insertBicycleCreditCardRecords(bankCardNo,new Date(),2,1);
                    return false;
                }
                //判断该卡有没有正在租车记录结束
                if (bicycleStatus != 1){
                    log.error("自行车状态不正确");
                    return false;
                }
                Integer cardType =0;
                Integer UcType = unlockMapper.selectUniversalCardTypeByRiderId(riderId);
                if (!StringUtils.isEmpty(UcType)){
                    cardType = UcType;
                }
                if (cardType==2){
                    ctx.channel().writeAndFlush(ss);
                }else {
                    int count5 = unlockMapper.selectCountA15riderForegift(riderId);
                    BigDecimal amount = new BigDecimal(0);
                    if (count5!=1){
                        amount=new BigDecimal(0);
                    }else {
                        BigDecimal foregiftAmount = unlockMapper.selectA15riderForegift(riderId);
                        amount=foregiftAmount;
                    }
                    if (amount.compareTo(new BigDecimal(200))==-1){
                        ctx.channel().writeAndFlush(s);
                        unlockMapper.insertBicycleCreditCardRecords(bankCardNo,new Date(),2,1);
                        return false;
                    }else {
                        if (cardType==0){
                            int count6 = unlockMapper.selectCountA02account(riderId);
                            BigDecimal balance = new BigDecimal(0);
                            if (count6!=1){
                                balance= new BigDecimal(0);
                            }else {
                                BigDecimal A02Balance  = unlockMapper.selectA02account(riderId);
                                balance = A02Balance;
                            }
                            if (balance.compareTo(new BigDecimal(5))==-1){
                                ctx.channel().writeAndFlush(s);
                                unlockMapper.insertBicycleCreditCardRecords(bankCardNo,new Date(),2,1);
                                return false;
                            }
                        }
                    }
                }
                //是不是新站点
                //获取自行车号、运营商id、自行车状态
                Integer type = unlockMapper.selectBicycleDocksiteType(dockSiteNo);
                if (StringUtils.isEmpty(type)){
                    log.error("站点类型不存在");
                    return false;
                }
                unlockMapper.insertBicycleRent(riderId,bicycleNo,new Date(),0,new Date(),dockSiteNo,strBankUUid.toString(),operatorId,timeCharge,1,1, dockSiteId);
                if (type==1){
                    unlockMapper.updateBicycleDockSite(new Date(),dockSiteNo);
                }else {
                    unlockMapper.updateBicycleDockSiteTwo(new Date(),dockSiteNo);
                }
                unlockMapper.updateBicycleStatusAndDockSiteNo(lockNo, String.valueOf(operatorId));
                unlockMapper.insertBicycleCreditCardRecords(bankCardNo,new Date(),2,1);
                ctx.channel().writeAndFlush(ss);
            }
        }
        return false;
    }
}
